/*
 * Copyright 2013 Agustina Martinez-Garcia

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package uk.ljmu.qudex.qudexservlet.servlets;

//import java.io.FileNotFoundException;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import uk.ljmu.mulgaraifz.errorhandling.MulgaraException;
import uk.ljmu.qudex.qudexservlet.mulgara.ISparqlMulgara;
import uk.ljmu.qudex.qudexservlet.mulgara.SparqlMulgaraImpl;

public class SparqlServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7288158115691767707L;

	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		// Use a ServletOutputStream because we may pass binary information
		ServletOutputStream out = res.getOutputStream();
		ISparqlMulgara mulg;
		// Get the file to view
		// String file = req.getPathTranslated();
		String collectionId = req.getParameter("collection");
		int operation = Integer.parseInt(req.getParameter("operation"));
		res.setContentType("application/json");
		try {
			switch (operation) {
			case 1:
				mulg = new SparqlMulgaraImpl();
				mulg.generateCollectionsJsonFile(collectionId, out);
				break;
			case 2:
				mulg = new SparqlMulgaraImpl();
				mulg.generateDocumentsJsonFile(collectionId, out);
				break;
			case 3:
				mulg = new SparqlMulgaraImpl();
				mulg.generateCategoriesJsonFile(collectionId, out);
				break;
			default: 
				break;
			}
		} catch (MulgaraException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			out.close();
		}
		
		// No file, nothing to view
		//if (file == null) {
		//	out.println("No file to view");
		//	return;
		//}

		// Get and set the type of the file
		//String contentType = getServletContext().getMimeType(file);
		//res.setContentType(contentType);

		// Return the file
		//try {
		//	ServletUtils.returnFile(file, out);
		//} catch (FileNotFoundException e) {
		//	out.println("File not found");
		//} catch (IOException e) {
		//	out.println("Problem sending file: " + e.getMessage());
		//}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

}